package StudyCode.summary.BufferAndChannel;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CopyFileUsingFileChannelAndDirectByteBuffer {
	public static void main(String[] args) {
		Path copy_from = Paths.get("E:\\Copy", "1.txt");
		Path copy_to = Paths.get("E:/Copy/2.txt");
		int bufferSizeKB = 4;
		int bufferSize = bufferSizeKB * 1024;
		System.out.println("使用 FileChannel 和 ByteBuffer 类复制文件 ...");
		try (FileChannel fileChannel_from = (FileChannel.open(copy_from,
				EnumSet.of(StandardOpenOption.READ)));
		     FileChannel fileChannel_to = (FileChannel
				     .open(copy_to, EnumSet.of(StandardOpenOption.CREATE_NEW,
						     StandardOpenOption.WRITE)))) {
			ByteBuffer bytebuffer = ByteBuffer.allocateDirect(bufferSize);
			int bytesCount;
			while ((bytesCount = fileChannel_from.read(bytebuffer)) > 0) {
				bytebuffer.flip();
				fileChannel_to.write(bytebuffer);
				bytebuffer.clear();
			}
			System.out.println("使用 FileChannel 和 ByteBuffer 类复制文件成功");
		} catch (IOException ex) {
			System.err.println(ex);
		}
	}
}
